package com.moo2u2.android.oaktononthego.crm;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.moo2u2.android.oaktononthego.R;
import com.moo2u2.android.oaktononthego.crm.dao.CustomerDbAdapter;
import com.moo2u2.android.oaktononthego.crm.dao.CustomerTable;
import com.moo2u2.android.oaktononthego.crm.dao.OpportunityTable;

public class CRMDetail extends Activity {
	public static final String MODE = "MODE";

	public static enum Mode {
		READ, EDIT
	};

	public static final String FILENAME = "OaktonCrmImage";

	public static final int ACTIVITY_SELECT_IMAGE = 1;
	public static final int ACTIVITY_TAKE_PICTURE = 2;

	public static final int SELECT_PHOTO = 3;
	public static final int TAKE_PHOTO = 4;

	public static final int EDIT = 5;
	public static final int SAVE = 6;
	public static final int DELETE = 7;

	private Long mRowId = null;

	private CustomerDbAdapter dbHelper;

	private LinearLayout opportunities;

	private TextView nameText;
	private TextView contactText;
	private TextView phoneText;
	private TextView faxText;
	private TextView emailText;
	private TextView addressText;
	private TextView winsText;
	private TextView lossesText;
	private TextView descriptionText;
	private TextView notesText;

	private ImageView profilePic;

	private Mode mode = Mode.READ;

	File photo = new File(Environment.getExternalStorageDirectory(),
			"camera_pic.jpg");
	Uri tempImage;

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

		Bundle extras = getIntent().getExtras();
		mRowId = (bundle == null) ? null : (Long) bundle
				.getSerializable(CustomerTable.KEY_ROWID);
		mode = (bundle == null) ? Mode.READ : (Mode) bundle
				.getSerializable(MODE);
		if (extras != null) {
			mRowId = extras.getLong(CustomerTable.KEY_ROWID);
			mode = (Mode) extras.getSerializable(MODE);
		}

		dbHelper = new CustomerDbAdapter(this);
		dbHelper.open();

		initFields(bundle);

		if (customTitleSupported)
			getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
					R.layout.window_title);

	}

	private void initFields(Bundle savedData) {
		if (Mode.EDIT.equals(mode))
			initEdit();
		else
			initRead();

		nameText = (TextView) findViewById(R.id.profile_name);
		contactText = (TextView) findViewById(R.id.profile_contact);
		phoneText = (TextView) findViewById(R.id.profile_phone);
		faxText = (TextView) findViewById(R.id.profile_fax);
		emailText = (TextView) findViewById(R.id.profile_email);
		addressText = (TextView) findViewById(R.id.profile_address);
		winsText = (TextView) findViewById(R.id.profile_wins);
		lossesText = (TextView) findViewById(R.id.profile_losses);
		descriptionText = (TextView) findViewById(R.id.profile_description);
		notesText = (TextView) findViewById(R.id.profile_notes);
		if (!Mode.EDIT.equals(mode)) {
			opportunities = (LinearLayout) findViewById(R.id.profile_opportunities);
		}

		populateFields(savedData);
	}

	private void initRead() {
		setContentView(R.layout.crm_detail);
		profilePic = (ImageView) findViewById(R.id.profile_pic);
		File pic = new File(getFilesDir().getAbsolutePath() + File.separator
				+ CRMDetail.FILENAME + mRowId);
		if (pic.exists())
			profilePic.setImageBitmap(BitmapFactory.decodeFile(pic
					.getAbsolutePath()));
		else
			profilePic.setImageDrawable(getResources().getDrawable(
					R.drawable.defaultphoto));

		((ImageView) findViewById(R.id.profile_call))
				.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						startActivity(new Intent(Intent.ACTION_DIAL, Uri
								.parse("tel:" + phoneText.getText())));
					}
				});

		((ImageView) findViewById(R.id.profile_sms))
				.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						String url = "smsto:" + phoneText.getText();
						Intent smsIntent = new Intent(Intent.ACTION_SENDTO, Uri
								.parse(url));
						// smsIntent.putExtra("sms_body", "Body text");
						startActivity(smsIntent);
					}
				});

		((ImageView) findViewById(R.id.profile_fax_call))
				.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						startActivity(new Intent(Intent.ACTION_DIAL, Uri
								.parse("tel:" + faxText.getText())));
					}
				});

		((ImageView) findViewById(R.id.profile_fax_sms))
				.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						String url = "smsto:" + faxText.getText();
						Intent smsIntent = new Intent(Intent.ACTION_SENDTO, Uri
								.parse(url));
						// smsIntent.putExtra("sms_body", "Body text");
						startActivity(smsIntent);
					}
				});

		((ImageView) findViewById(R.id.profile_email_send))
				.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						Intent emailIntent = new Intent(Intent.ACTION_SEND);

						emailIntent.setType("plain/text");
						emailIntent
								.putExtra(android.content.Intent.EXTRA_EMAIL,
										new String[] { emailText.getText()
												.toString() });
						// emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
						// "Subject");
						// emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,"Text");

						startActivity(Intent.createChooser(emailIntent,
								"Send mail..."));
					}
				});

		((ImageView) findViewById(R.id.profile_maps))
				.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						startActivity(new Intent(Intent.ACTION_VIEW, Uri
								.parse("geo:0,0?q=:" + addressText.getText())));
					}
				});

		((ImageView) findViewById(R.id.profile_add_opportunity))
				.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						addOpportunity(CRMDetail.this);
					}
				});
	}

	private void initEdit() {
		setContentView(R.layout.crm_detail_edit);

		profilePic = (ImageView) findViewById(R.id.profile_pic);
		File pic = new File(getFilesDir().getAbsolutePath() + File.separator
				+ CRMDetail.FILENAME + mRowId);
		if (pic.exists())
			profilePic.setImageBitmap(BitmapFactory.decodeFile(pic
					.getAbsolutePath()));
		else
			profilePic.setImageDrawable(getResources().getDrawable(
					R.drawable.defaultphoto));
		registerForContextMenu(profilePic);
		profilePic.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				openContextMenu(v);
			}
		});

		((Button) findViewById(R.id.save_customer))
				.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						saveCustomer();
						setResult(RESULT_OK);
						finish();
					}
				});
	}

	private void populateFields(Bundle savedData) {
		if (savedData != null) {
			tempImage = (savedData.getString("img") == null) ? null : Uri
					.parse(savedData.getString("img"));
			if (tempImage != null)
				setImage();
		}
		if (mRowId != null && mRowId != 0) {
			Cursor customerDetails = dbHelper.fetchCustomer(mRowId);

			String lossesTxt = customerDetails.getString(customerDetails
					.getColumnIndexOrThrow(CustomerTable.KEY_LOSSES));
			String winsTxt = customerDetails.getString(customerDetails
					.getColumnIndexOrThrow(CustomerTable.KEY_WINS));

			nameText.setText(customerDetails.getString(customerDetails
					.getColumnIndexOrThrow(CustomerTable.KEY_NAME)));
			contactText.setText(customerDetails.getString(customerDetails
					.getColumnIndexOrThrow(CustomerTable.KEY_CONTACT)));
			phoneText.setText(customerDetails.getString(customerDetails
					.getColumnIndexOrThrow(CustomerTable.KEY_PHONE)));
			faxText.setText(customerDetails.getString(customerDetails
					.getColumnIndexOrThrow(CustomerTable.KEY_FAX)));
			emailText.setText(customerDetails.getString(customerDetails
					.getColumnIndexOrThrow(CustomerTable.KEY_EMAIL)));
			addressText.setText(customerDetails.getString(customerDetails
					.getColumnIndexOrThrow(CustomerTable.KEY_ADDRESS)));
			winsText.setText((winsTxt == null || "".equals(winsTxt)) ? "0"
					: winsTxt);
			lossesText
					.setText((lossesTxt == null || "".equals(lossesTxt)) ? "0"
							: lossesTxt);
			if (Mode.READ.equals(mode)) {
				winsText.setText("W: " + winsText.getText());
				lossesText.setText(" / L: " + lossesText.getText());
			}
			descriptionText.setText(customerDetails.getString(customerDetails
					.getColumnIndexOrThrow(CustomerTable.KEY_DESCRIPTION)));
			notesText.setText(customerDetails.getString(customerDetails
					.getColumnIndexOrThrow(CustomerTable.KEY_NOTES)));
			customerDetails.deactivate();
			customerDetails.close();

			Cursor opportunityDetails = dbHelper.fetchOpportunities(mRowId);
			if (opportunities != null)
				opportunities.removeAllViews(); // remove deleted
			if (opportunityDetails != null) {
				LinearLayout opportunityRow;
				do {
					final long rowId = opportunityDetails
							.getLong(opportunityDetails
									.getColumnIndexOrThrow(OpportunityTable.KEY_ROWID));
					opportunityRow = (LinearLayout) getLayoutInflater()
							.inflate(R.layout.opportunity_row,
									(ViewGroup) opportunities, true);
					TextView opportunityTxt = (TextView) opportunityRow
							.findViewById(R.id.opportunity);
					opportunityTxt
							.setText(opportunityDetails.getString(opportunityDetails
									.getColumnIndexOrThrow(OpportunityTable.KEY_DESC)));
					ImageView opportunityImg = (ImageView) opportunityRow
							.findViewById(R.id.del_opportunity);
					opportunityImg.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							if (!dbHelper.deleteOpportunity(rowId)) {
								Toast.makeText(CRMDetail.this,
										"Error deleting opportunity",
										Toast.LENGTH_SHORT).show();
							}
							populateFields(null);
						}
					});
					opportunityTxt.setId(0);
					opportunityImg.setId(0);
				} while (opportunityDetails.moveToNext());

				opportunityDetails.deactivate();
				opportunityDetails.close();
			}
		}
	}

	private void addOpportunity(Context ctx) {
		AlertDialog.Builder alert = new AlertDialog.Builder(ctx);
		alert.setTitle("New Opportunity");
		alert.setMessage("Add an opportunity:");

		final EditText oppValue = new EditText(ctx);
		alert.setView(oppValue);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dbHelper.addOpportunity(mRowId, oppValue.getText().toString());
				populateFields(null);
			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.
					}
				});

		alert.show();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(Menu.NONE, SELECT_PHOTO, Menu.NONE, R.string.select_photo);
		menu.add(Menu.NONE, TAKE_PHOTO, Menu.NONE, R.string.take_photo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case SELECT_PHOTO:
			Intent i = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(i, ACTIVITY_SELECT_IMAGE);
			return true;
		case TAKE_PHOTO:
			Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
			tempImage = Uri.fromFile(photo);
			startActivityForResult(intent, ACTIVITY_TAKE_PICTURE);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		outState.putLong(CustomerTable.KEY_ROWID, mRowId);

		if (tempImage != null)
			outState.putString("img", tempImage.toString());
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (dbHelper != null) {
			dbHelper.close();
		}
	}

	private void saveCustomer() {
		String name = nameText.getText().toString();
		String contact = contactText.getText().toString();
		String phone = phoneText.getText().toString();
		String fax = faxText.getText().toString();
		String email = emailText.getText().toString();
		String address = addressText.getText().toString();
		Integer wins = ("".equals(winsText.getText().toString())) ? null
				: Integer.valueOf(winsText.getText().toString());
		Integer losses = ("".equals(lossesText.getText().toString())) ? null
				: Integer.valueOf(lossesText.getText().toString());
		String description = descriptionText.getText().toString();
		String notes = notesText.getText().toString();

		if (mRowId == null || mRowId == 0) {
			long id = dbHelper.createCustomer(name, contact, phone, fax, email,
					address, wins, losses, description, notes);
			if (id > 0) {
				mRowId = id;
			}
		} else {
			dbHelper.updateCustomer(mRowId, name, contact, phone, fax, email,
					address, wins, losses, description, notes);
		}
		Toast.makeText(this, "Customer saved", Toast.LENGTH_SHORT).show();

		FileOutputStream fOut;
		try {
			fOut = openFileOutput(FILENAME + mRowId, Context.MODE_PRIVATE);
			((BitmapDrawable) profilePic.getDrawable()).getBitmap().compress(
					Bitmap.CompressFormat.PNG, 100, fOut);
			fOut.flush();
			fOut.close();
		} catch (Exception e) {
			Log.e(this.getClass().getSimpleName(), "Error saving profile pic",
					e);
			Toast.makeText(this, "Error saving picture", Toast.LENGTH_SHORT)
					.show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.clear();
		if (Mode.EDIT.equals(mode)) {
			menu.add(Menu.NONE, SAVE, Menu.NONE, R.string.save).setIcon(
					android.R.drawable.ic_menu_save);
		} else {
			menu.add(Menu.NONE, EDIT, Menu.NONE, R.string.edit).setIcon(
					android.R.drawable.ic_menu_edit);
		}
		menu.add(Menu.NONE, DELETE, Menu.NONE, R.string.delete).setIcon(
				android.R.drawable.ic_menu_delete);
		return true;
	}

	/** {@inheritDoc} */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case SAVE:
			saveCustomer();
			setResult(RESULT_OK);
			finish();
			return true;
		case EDIT:
			mode = Mode.EDIT;
			initFields(null);
			return true;
		case DELETE:
			if (mRowId != null && mRowId != 0)
				dbHelper.deleteCustomer(mRowId);
			finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case ACTIVITY_SELECT_IMAGE:
			if (resultCode == RESULT_OK) {
				tempImage = data.getData();
				setImage();
			}
		case ACTIVITY_TAKE_PICTURE:
			if (resultCode == Activity.RESULT_OK) {
				getContentResolver().notifyChange(tempImage, null);
				setImage();
			}
		}
	}

	private void setImage() {
		// String[] filePathColumn = { MediaStore.Images.Media.DATA };
		// Cursor cursor = getContentResolver().query(tempImage,
		// filePathColumn, null, null, null);
		// cursor.moveToFirst();
		// int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
		// String filePath = cursor.getString(columnIndex);
		// cursor.close();
		//
		// profilePic.setImageDrawable(Drawable.createFromPath(filePath));

		// ----

		ContentResolver cr = getContentResolver();
		Bitmap bitmap;
		try {
			bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr,
					tempImage);

			profilePic.setImageBitmap(bitmap);
		} catch (FileNotFoundException e) {
			Toast.makeText(this, "Error locating picture", Toast.LENGTH_SHORT)
					.show();
			Log.e("Camera locate", e.toString());
		} catch (IOException e) {
			Toast.makeText(this, "Error loading picture", Toast.LENGTH_SHORT)
					.show();
			Log.e("Camera load", e.toString());
		}
	}
}
